package com.cctcq.util.jdbc;



public class PageUtil {

	// Use the origin page to create a new page

	public static Page createPage(Page page, int totalRecords) {
		return createPage(page.getEveryPage(), page.getCurrentPage(),totalRecords);
	}
	public static Page createPage(Page page, int totalRecords,String url) {
		return createPage(page.getEveryPage(), page.getCurrentPage(),totalRecords,url);
	}
	public static Page createPage(int everyPage, int currentPage,
			int totalRecords) {
		everyPage = getEveryPage(everyPage);
		currentPage = getCurrentPage(currentPage);
		int beginIndex = getBeginIndex(everyPage, currentPage);
		int totalPage = getTotalPage(everyPage, totalRecords);
		int nextPage = hasNextPage(currentPage, totalPage);
		int backPage = hasPrePage(currentPage);
		return new Page(everyPage, totalPage, currentPage, beginIndex,
				totalRecords, backPage, nextPage);
	}
	public static Page createPage(int everyPage, int currentPage,
			int totalRecords,String url) {
		everyPage = getEveryPage(everyPage);
		currentPage = getCurrentPage(currentPage);
		int beginIndex = getBeginIndex(everyPage, currentPage);
		int totalPage = getTotalPage(everyPage, totalRecords);
		int nextPage = hasNextPage(currentPage, totalPage);
		int backPage = hasPrePage(currentPage);
		return new Page(everyPage, totalPage, currentPage, beginIndex,
				totalRecords, backPage, nextPage,url);
	}
	private static int getEveryPage(int everyPage) {
		return everyPage == 0 ? 10 : everyPage;
	}

	private static int getCurrentPage(int currentPage) {
		return currentPage == 0 ? 1 : currentPage;
	}

	private static int getBeginIndex(int everyPage, int currentPage) {
		return (currentPage - 1) * everyPage;
	}

	private static int getTotalPage(int everyPage, int totalRecords) {
		int totalPage = 0;

		if (totalRecords % everyPage == 0)
			totalPage = totalRecords / everyPage;
		else
			totalPage = totalRecords / everyPage + 1;

		return totalPage;
	}

	private static int hasPrePage(int currentPage) {
		if (currentPage <= 1) {
			return 1;
		} else {
			return currentPage - 1;
		}

	}

	private static int hasNextPage(int currentPage, int totalPage) {
		if (currentPage >= totalPage) {
			return totalPage;
		} else {
			return currentPage + 1;
		}
	}

}
